<template>
  <BasicDrawer v-bind="$attrs" :title="title" width="50%" @register="register">
    <div class="h-screen flex flex-col">
      <BasicForm @register="registerForm" class="flex-1"> </BasicForm>
      <Divider v-if="title !== '添加'">提醒记录</Divider>
      <div class="flex-1">
        <BasicTable v-if="title !== '添加'" class="h-full" @register="registerTable">
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'remiderType'">
              <div class="flex justify-center">
                <div
                  :style="{
                    background:
                      record[`${column.key}`] === 2
                        ? '#ff4a4a'
                        : record[`${column.key}`] === 1
                          ? '#fff050'
                          : record[`${column.key}`] === 0
                            ? '#7bfd53'
                            : record[`${column.key}`] === -1
                              ? '#ffffff'
                              : '#000000',
                    width: '20px',
                    height: '20px',
                    borderRadius: '50%',
                  }"
                ></div>
              </div>
            </template>
            <template v-if="column.key === 'action'">
              <TableAction
                :actions="[
                  {
                    label: '编辑',
                    onClick: handleEdit.bind(null, record),
                    disabled: title === '详情' ? true : false,
                  },
                  {
                    label: '详情',
                    onClick: handleDetail.bind(null, record),
                  },
                  {
                    label: '办结',
                    onClick: handleConclude.bind(null, record),
                    disabled: record.isCompletion === 1,
                  },
                ]"
              />
            </template>
          </template>
          <template #toolbar>
            <div class="flex" v-if="title == '编辑'">
              <a-button
                type="primary"
                class="flex items-center"
                @click="
                  openModal(true, {
                    title: '添加',
                    id: details,
                  })
                "
              >
                添加
              </a-button>
            </div>
          </template>
        </BasicTable>
      </div>
    </div>
    <Modal @register="registerModal" @next="handleChange" />
  </BasicDrawer>
</template>
<script lang="ts" setup>
  import { Divider } from 'ant-design-vue';
  import { ref } from 'vue';

  import {
    // getSearchSources,
    completionReminder,
    getManagementCreate,
    getManagementUpdate,
    // getSearchDevices,
    getSearchServiceReminder,
  } from '@/api/page/manage_account';
  import { BasicDrawer, useDrawerInner } from '@/components/Drawer';
  import { BasicForm, useForm } from '@/components/Form/index';
  import { useModal } from '@/components/Modal';
  import { BasicTable, TableAction, useTable } from '@/components/Table';
  import { useMessage } from '@/hooks/web/useMessage';

  import { sourceOption, deviceOption, deviceModelOption } from '../data';
  import { detailSchemas, getBasicColumns } from './data';
  import { searchReturnReasons } from '@/api/page/return_reason';
  import Modal from './Modal.vue';

  const emit = defineEmits(['next', 'register']);
  const { createMessage, createConfirm } = useMessage();
  // const getTitle = computed(() => title.value);
  const title = ref<string>('');
  const details = ref<object>({});

  const [registerForm, { setFieldsValue, updateSchema, setProps, validate, resetFields }] = useForm(
    {
      labelWidth: 120,
      // schemas: detailSchemas,
      // layout: 'vertical',
      actionColOptions: {
        span: 24,
      },
      // showActionButtonGroup: false,
      showResetButton: false,
      showSubmitButton: true,
      submitButtonOptions: {
        text: '提交',
      },
      submitFunc: customSubmitFunc,
    },
  );

  async function customSubmitFunc() {
    try {
      const values = await validate();
      if (title.value === '添加') {
        getManagementCreate(values).then((res) => {
          if (res.code === 1000) {
            createMessage.success('添加成功！');
            emit('next', values);
          } else {
            createMessage.error('添加失败，请重试！');
          }
        });
      } else {
        const params = Object.assign({}, details.value, values);
        getManagementUpdate(params).then((res) => {
          if (res.code === 1000) {
            createMessage.success('修改成功！');
            emit('next', values);
          } else {
            createMessage.error('修改失败，请重试！');
          }
        });
      }
    } catch (error) {
      console.log('error', error);
      createMessage.error('请将有红色标记的填写完整');
    }
  }

  // 服务记录
  const updateForm = (deviceOption, selectDeviceModelOption, bool: boolean) => {
    return detailSchemas.map((item) => {
      item.componentProps = {
        ...item.componentProps,
        disabled: bool,
      };
      if (item.field === 'device') {
        item.componentProps = () => {
          return {
            ...(item.componentProps || {}),
            options: [...deviceOption],
            disabled: bool,
            onChange: (e: any) => {
              let selectDeviceModel: any[] = [];
              selectDeviceModel = deviceModelOption.value.filter((item) => {
                return item.device === e;
              });
              updateSchema({
                field: 'deviceModel',
                componentProps: {
                  options: selectDeviceModel,
                },
              });
            },
          };
        };
      }
      if (item.field === 'source') {
        item.componentProps = {
          ...(item.componentProps || {}),
          options: sourceOption.value,
        };
      }
      if (item.field === 'deviceModel' && selectDeviceModelOption.length > 0) {
        item.componentProps = {
          ...item.componentProps,
          options: selectDeviceModelOption,
        };
      }

      return {
        ...item,
      };
    });
  };

  const customerManagentId = ref<object>({});
  const [register] = useDrawerInner((data) => {
    setProps({
      showSubmitButton: data.title === '详情' ? false : true,
      schemas: updateForm(
        deviceOption.value.length > 0 ? deviceOption.value : [],
        deviceModelOption.value,
        data.title === '详情' ? true : false,
      ),
    });

    resetFields();
    title.value = data.title;
    details.value = data.record || {};

    // 退货
    searchReturnReasons({}).then((res) => {
      if (res.code === 1000) {
        let option = <any>[];
        res.obj.forEach((item) => {
          option.push({
            label: item.returnReasons,
            value: item.returnReasons,
            key: item.returnReasons,
          });
        });
        updateSchema({
          field: 'returnReason',
          componentProps: {
            options: option,
          },
        });
      }
    });

    if (data?.record) {
      setFieldsValue({
        ...data.record,
      });
    }

    if (data.record && data.record.id) {
      customerManagentId.value = data.record.id;
      handleGetSearchServiceReminder({ customerManagentId: data.record.id });
    }
  });

  const [registerModal, { openModal }] = useModal();
  const list = ref<any[]>([]);
  async function handleGetSearchServiceReminder(param) {
    const data = await getSearchServiceReminder(param);
    if (data.code === 1000) {
      setTableData(data.obj);
      list.value = data.obj;
    }
  }
  const [registerTable, { setTableData }] = useTable({
    dataSource: list.value,
    // api: apiList,
    columns: getBasicColumns,
    showTableSetting: false,
    showIndexColumn: false,
    rowKey: 'id',
    canResize: false,
    rowSelection: {
      type: 'checkbox',
    },
    actionColumn: {
      title: '操作',
      dataIndex: 'action',
      fixed: 'right',
    },
  });

  function handleEdit(record) {
    openModal(true, {
      title: '编辑',
      record,
      id: details.value,
    });
  }
  function handleDetail(record) {
    openModal(true, {
      title: '详情',
      record,
      details: true,
      id: details.value,
    });
  }

  function handleConclude(record) {
    createConfirm({
      iconType: 'info',
      title: () => '办结提醒',
      content: () => '确定要办结该内容吗',
      onOk: () => {
        completionReminder({ id: record.id }).then((res) => {
          if (res.code === 1000) {
            createMessage.success('办结成功！');
            handleGetSearchServiceReminder({ customerManagentId: customerManagentId.value });
          } else {
            createMessage.error('办结失败，请重试！');
          }
        });
      },
    });
  }
  function handleChange() {
    handleGetSearchServiceReminder({ customerManagentId: customerManagentId.value });
  }
</script>
